package io.sundial.job.bind.impl;

import io.sundial.job.JobContext;
import io.sundial.job.JobParameter;
import io.sundial.job.bind.JobData;
import io.sundial.job.bind.JobField;
import io.sundial.job.bind.JobResolver;
import io.sundial.util.StrKit;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 枚举 转换器
 *
 * @author Payne 646742615@qq.com
 * 2019/1/7 21:26
 */
public class EnumResolver implements JobResolver {

    @Override
    public boolean supports(JobField field) {
        return field.type.isEnum();
    }

    @Override
    public JobParameter resolve(JobField field) {
        Enum<?>[] constants = field.type.asSubclass(Enum.class).getEnumConstants();
        Map<String, String> options = new LinkedHashMap<>();
        for (Enum<?> constant : constants) options.put(constant.name(), constant.name());
        String value = field.value != null ? field.value.toString() : null;
        return new JobParameter(field.name)
                .setEditor("select")
                .setOptions(options)
                .setValue(value);
    }

    @Override
    public Object resolve(JobField field, JobData data, JobContext context) {
        String value = data.get(field.name);
        return StrKit.isEmpty(value) ? DEFAULT : Enum.valueOf(field.type.asSubclass(Enum.class), value);
    }
}
